<template>
  <div class="image-library-container">
    <!-- 顶部控制区 -->
    <div class="controls">
      <!-- 搜索框 -->
      <div class="search-container">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索图片..." 
          class="search-input"
        />
        <img 
          src="@/assets/picture/find.png" 
          @click="filterImages" 
          alt="搜索" 
          class="search-icon" 
        />
        <button style="margin-left: 20px;" class="btn upload-btn" @click="selectFile">上传图片</button>
        <!-- 隐藏的文件选择器 -->
        <input type="file" ref="fileInput" @change="handleFileChange" accept=".jpg,.png,.jpeg" style="display: none" />
      </div>
    </div>

    <!-- 图片展示区 -->
    <div class="image-gallery">
      <div 
        v-for="(image) in paginatedImages" 
        :key="image.resource_id" 
        @click="handleSelect(image)"
        class="image-item"
      >
        <div class="image-container" @click="openImage(image.resource_url)">
          <img :src="image.resource_url" :alt="image.resource_name" class="gallery-image" />
          <div class="button-group">
            <button class="btn delete-btn" @click.stop="deleteImage(image.resource_id)">✖</button>
          </div>
        </div>
        <div class="image-details" style="width:100%" @click="startRenaming(image)">
          <span v-if="!image.isEditing" class="image-name" @click="startRenaming(image)">{{ image.resource_name }}</span>
          <input 
            v-if="image.isEditing" 
            type="text" 
            v-model="image.newName" 
            @blur="confirmRename(image)"
            @keyup.enter="confirmRename(image)"
            class="rename-input"
          />
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button class="btn" @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>当前页: {{ currentPage }} / {{ totalPages }}</span>
      <button class="btn" @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { upload, apiDeleteResource, apiRenameResource, fetchResourcesByType } from '@/services/api';

export default {
  name: 'T_ImagesPage',
  setup(props, context) {
    const router = useRouter();
    const techId = ref(null);
    const token = ref(null);
    const currentPage = ref(1);
    const itemsPerPage = 15;
    const images = ref([]);
    const filteredImages = ref([]);
    const searchQuery = ref('');
    const fileInput = ref(null);
    const file = ref(null);

    const handleSelect = (image) => {  
      const selectedImage = {
        id: image.resource_id,         
        name: image.resource_name,
        type: 'image',                
        uploadTime: image.update_time,
        url: image.resource_url
      };
      context.emit('image-selected', selectedImage);
    };

    const fetchImageResources = () => {
      if (!techId.value) {
        console.error('Tech ID is missing. Redirecting to login page.');
        router.push('/login');
        return;
      }

      fetchResourcesByType(techId.value, 'pic', token.value)
        .then(response => {
          if (response.data.status === 1) {
            images.value = response.data.data;
            filteredImages.value = images.value;
          } else {
            console.error('获取图片失败:', response.data.msg);
            if (response.data.status === 'NOT_LOGIN') {
              router.push('/login');
            }
          }
        })
        .catch(error => {
          console.error('请求错误:', error);
        });
    };

    const selectFile = () => {
      if (fileInput.value) {
        fileInput.value.click();
      }
    };

    const handleFileChange = (event) => {
      const selectedFile = event.target.files[0];
      if (!selectedFile) {
        return;
      }
      file.value = selectedFile;
      uploadResource();
    };

    const uploadResource = () => {
      const formData = new FormData();
      formData.append('tech_id', techId.value);
      formData.append('resource_type', getFileType(file.value));
      formData.append('file', file.value);

      upload(formData)
        .then(response => {
          console.log('文件上传成功:', response.data);
          ElMessage.success('文件上传成功！');
          fetchImageResources();
        })
        .catch(error => {
          console.error('文件上传失败:', error);
          ElMessage.error('文件上传失败，请重试。');
        });
    };

    const getFileType = (file) => {
      const extension = file.name.split('.').pop().toLowerCase();
      if (['png', 'jpg', 'jpeg'].includes(extension)) {
        return 'pic';
      } else {
        return 'other';
      }
    };

    const filterImages = () => {
      if (searchQuery.value) {
        filteredImages.value = images.value.filter(image =>
          image.resource_name.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
      } else {
        filteredImages.value = images.value;
      }
      currentPage.value = 1; // 重置到第一页
    };

    const paginatedImages = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredImages.value.slice(start, end);
    });

    const totalPages = computed(() => Math.ceil(filteredImages.value.length / itemsPerPage));

    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++;
      }
    };

    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };

    const startRenaming = (image) => {
      image.isEditing = true;
      image.newName = image.resource_name;

      // 添加事件监听器以处理点击空白处取消或提交
      const handleClick = (e) => {
        const isClickInside = e.target.closest('.image-details');
        if (!isClickInside && image.isEditing) {
          confirmRename(image);
          document.removeEventListener('click', handleClick);
        }
      };
      document.addEventListener('click', handleClick);
    };

    const confirmRename = (image) => {
      if (image.newName.trim() && image.newName !== image.resource_name) {
        apiRenameResource(image.resource_id, image.newName)
          .then(response => {
            if (response.data.status === 1) {
              image.resource_name = image.newName;
              ElMessage.success('重命名成功！');
            } else {
              ElMessage.error('重命名失败，请重试。');
            }
          })
          .catch(error => {
            console.error('重命名请求错误:', error);
            ElMessage.error('重命名失败，请检查网络或稍后重试。');
          });
      }
      image.isEditing = false;
    };

   const deleteImage = async (imageId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除此图片吗？',
      '警告',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    console.log('Deleting image with ID:', imageId);
    const response = await apiDeleteResource(imageId);
    
    if (response.data.status === 1) {
      ElMessage.success('图片删除成功');
      images.value = images.value.filter(image => image.resource_id !== imageId);
      filterImages();
    } else {
      console.error('删除失败:', response.data.msg);
      ElMessage.error('删除失败，请重试。');
    }
  } catch (error) {
    // 用户取消操作自动捕获，无需处理
  }
};

    const openImage = (ImageUrl) => {
      window.open(ImageUrl, "_blank");
    };
    onMounted(() => {
      console.log('fileInput:', fileInput.value);
      const storedTechId = localStorage.getItem('id');
      const storedToken = localStorage.getItem('token');

      if (storedTechId && storedToken) {
        techId.value = storedTechId;
        token.value = storedToken;
        fetchImageResources();
      } else {
        console.error('User is not logged in. Redirecting to login page.');
        router.push('/login');
      }
    });

    return {
      techId,
      token,
      currentPage,
      itemsPerPage,
      images,
      fileInput,
      filteredImages,
      paginatedImages,
      totalPages,
      searchQuery,
      selectFile,
      handleFileChange,
      filterImages,
      nextPage,
      prevPage,
      startRenaming,
      confirmRename,
      deleteImage,
      openImage,
      uploadResource,
      handleSelect
    };
  },
};
</script>

<style scoped>
.image-library-container {
  padding: 20px;
}

.controls {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  margin-right: 20px;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  min-width: 200px;
  font-size: 16px;
  padding-right: 35px;
  border-radius: 20px;
  margin-right: 10px;
}

.search-icon {
  cursor: pointer;
  width: 20px; /* 图标的宽度 */
  height: 20px; /* 图标的高度 */
  margin-left: -40px; /* 将图标放置在输入框内 */
  margin-top: 7px;
}

.upload-btn {
  background-color: #125AA2;
  color: #fff;
  padding: 8px 12px; /* 添加合适的内边距 */
  border: none;
  border-radius: 4px; /* 圆角 */
  cursor: pointer;
  margin-left: 10px;
  transition: background-color 0.3s;
}

.upload-btn:hover {
  background-color: #3987d4; /* 悬停效果 */
}

.image-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
}

.image-item {
  position: relative;
  width: 150px;
  height: 200px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  border-radius: 8px;
  background-color: #fff;
  transition: border 0.3s ease; /* 添加边框变化效果 */
}

.image-container {
  position: relative;
  width: 120px;
  height: 100%;
  cursor: pointer; /* 鼠标悬停时显示手型 */
}

.gallery-image {
  width: 100%;
  height: 100%; /* 充满卡片内容 */
  object-fit: cover; /* 确保图片保持比例 */
  border-radius: 8px;
  transition: transform 0.3s ease; /* 添加缩放过渡效果 */
  margin-bottom:5px; ;
}

.image-item:hover .gallery-image {
  transform: scale(0.9); /* 鼠标经过时缩小图片 */
}

.image-item:hover {
  border: 2px solid #2196f3; /* 鼠标经过时显示边框 */
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
  width: 100%;
}

.delete-btn {
  position: absolute;
  top: 10px; /* 距离顶部 */
  right: 10px; /* 距离右侧 */
  background-color: transparent; /* 背景透明 */
  border: none; /* 无边框 */
  color: red; /* 红色 */
  font-size: 20px; /* 字体大小 */
  cursor: pointer; /* 鼠标悬停时显示手型 */
  transition: opacity 0.3s ease; /* 添加过渡效果 */
  opacity: 0; /* 初始隐藏 */
}

.image-item:hover .delete-btn {
  opacity: 1; /* 鼠标经过时显示按钮 */
}

.image-details {
  overflow: hidden; /* 溢出隐藏 */
  white-space: nowrap; /* 不换行 */
  text-overflow: ellipsis; /* 超出部分用省略号表示 */
  font-size: 12px;
  color: #527ebecc;
  /* background-color: #80808021; */
  width: 100%;
  text-align: center;
  height: 40px;
}

.image-name {
  max-width: 100%; /* 确保名字不超出 */
}

.rename-input {
  width: 100%;
  padding: 5px;
  margin-top: 10px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination button {
  padding: 8px 12px;
  margin: 0 5px;
  cursor: pointer;
  background-color: #2196f3;
  color: #fff;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.pagination button:disabled {
  background-color: #b0bec5;
  cursor: not-allowed;
}

.pagination span {
  font-size: 16px;
  color: #333;
}

/* 新增样式，使查看和删除按钮与上传按钮样式一致 */
.action-btn {
  background-color: #125AA2;
  color: #fff;
  padding: 8px 12px; /* 添加合适的内边距 */
  border: none;
  border-radius: 4px; /* 圆角 */
  cursor: pointer;
  transition: background-color 0.3s;
}

.action-btn:hover {
  background-color: #3987d4; /* 悬停效果 */
}
</style>
